package com.patch;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.patch.update.UpdateTask;

import java.util.concurrent.Executors;

/**
 * app更新
 */
public class AppUpdate {
    private static AppUpdate instance;

    // 单例模式
    public static synchronized AppUpdate getInstance() {
        if (instance == null) {
            instance = new AppUpdate();
        }
        return instance;
    }


    /**
     * @param type        1、自动更新
     * @param packageNmae 包名
     * @param apkPath     下载apk存放路径
     * @param updateUrl   app更新接口
     */
    public void appUpdate(int type, Context context, String packageNmae, String apkPath, String updateUrl) {
        if (type == 1) {
            new UpdateTask(UpdateTask.AUTO, context, packageNmae, apkPath, updateUrl).executeOnExecutor(Executors.newCachedThreadPool());
        } else {
            new UpdateTask(UpdateTask.MANU, context, packageNmae, apkPath, updateUrl).executeOnExecutor(Executors.newCachedThreadPool());
        }

    }

    public String getVersion(Context context) {

        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public String getOldApkPath(Context context, String packageNmae) {
        String appPath = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageNmae, 0);
            appPath = applicationInfo.sourceDir;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appPath;
    }

}
